<template>
  <div class="app-container">
	<div class="app-layout">
		<div class="pane" style="width: 100%;">
			<div class="head" style="padding-right: 8px;">
				<span>部门列表</span>
				<div style="flex: 1;"></div>
				<div>
					<el-button
					  v-hasPerm="['sys:dept:add']"
					  type="primary"
					  icon="plus"
					  @click="handleOpenDialog()"
					  size="small"
					>
					  新增
					</el-button>
					<el-button
					  v-hasPerm="['sys:dept:delete']"
					  type="danger"
					  :disabled="selectIds.length === 0"
					  icon="delete"
					  @click="handleDelete()"
					  size="small"
					>
					  删除
					</el-button>
				</div>
			</div>
			<div class="body">
				<div class="table-tool-bar">
					<div>
						<el-input
						  v-model="queryParams.keywords"
						  style="width:320px"
						  placeholder="输入部门名称进行搜索"
						  class="input-with-select"
						>
						  <template #append>
							<el-button icon="search"  @click="handleQuery" />
						  </template>
						</el-input>
					</div>
				</div>
				<div>
					<el-table
					  v-loading="loading"
					  :data="deptList"
					  row-key="id"
					  default-expand-all
					  :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
					  @selection-change="handleSelectionChange"
					  height="calc(100vh - 260px)"
					  border
					>
					  <el-table-column type="selection" width="55" align="center" />
					  <el-table-column prop="name" label="部门名称" align="left" width="300" />
					  <el-table-column prop="code" label="部门编号" align="left" width="200" />
					  <el-table-column prop="status" label="状态" width="100">
					    <template #default="scope">
					      <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
					      <el-tag v-else type="info">禁用</el-tag>
					    </template>
					  </el-table-column>
							<el-table-column prop="remark" align="left" label="备注"/>
					  <el-table-column prop="sort" label="排序" width="100" />
					
					  <el-table-column label="操作" fixed="right" align="left" width="200">
					    <template #default="scope">
					      <el-button
					        v-hasPerm="['sys:dept:add']"
					        type="primary"
					        link
					        size="small"
					        icon="plus"
					        @click.stop="handleOpenDialog(scope.row.id, undefined)"
					      >
					        新增
					      </el-button>
					      <el-button
					        v-hasPerm="['sys:dept:edit']"
					        type="primary"
					        link
					        size="small"
					        icon="edit"
					        @click.stop="handleOpenDialog(scope.row.parentId, scope.row)"
					      >
					        编辑
					      </el-button>
					      <el-button
					        v-hasPerm="['sys:dept:delete']"
					        type="danger"
					        link
					        size="small"
					        icon="delete"
					        @click.stop="handleDelete(scope.row.id)"
					      >
					        删除
					      </el-button>
					    </template>
					  </el-table-column>
					</el-table>
				</div>
			</div>
		</div> 
	</div>  

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      @closed="handleCloseDialog"
	  :close-on-click-modal="false"
    >
      <el-form ref="deptFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="上级部门" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            placeholder="选择上级部门"
            :data="deptOptions"
            filterable
            check-strictly
            :render-after-expand="false"
			:props="defaultProps"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门编号" prop="code">
          <el-input v-model="formData.code" placeholder="请输入部门编号" />
        </el-form-item>
        <el-form-item label="显示排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            style="width: 100px"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="部门状态">
          <el-radio-group v-model="formData.status">
            <el-radio :value="'1'">正常</el-radio>
            <el-radio :value="'0'">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
		
		<el-form-item label="备注" prop="remark">
		  <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" maxlength="250" />
		</el-form-item>
		
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Dept",
  inheritAttrs: false,
});

import DeptAPI, { DeptVO, DeptForm, DeptQuery } from "@/api/system/dept";
import {
  recurOptions
} from "@/utils/TreeUtil";
const queryFormRef = ref(ElForm);
const deptFormRef = ref(ElForm);
const defaultProps = {
  children: 'children',
  label: 'name',
  value:'id'
}
const loading = ref(false);
const selectIds = ref<number[]>([]);
const queryParams = reactive<DeptQuery>({});

const dialog = reactive({
  title: "",
  visible: false,
});

const deptList = ref<DeptVO[]>();
const deptOptions = ref<any[]>();
const formData = reactive<DeptForm>({
  status: '1',
  parentId: "-1",
  sort: 1,
});

const rules = reactive({
  parentId: [{ required: true, message: "上级部门不能为空", trigger: "change" }],
  name: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
  code: [{ required: true, message: "部门编号不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
});

// 查询部门
function handleQuery() {
  loading.value = true;
  DeptAPI.getList(queryParams).then((data) => {
    deptList.value = recurOptions(data,'-1');
    loading.value = false;
  });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

// 处理选中项变化
function handleSelectionChange(selection: any) {
  selectIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开部门弹窗
 *
 * @param parentId 父部门ID
 * @param row 部门ID
 */
async function handleOpenDialog(parentId?: string, row?: any) {
  // 加载部门下拉数据
  const data = recurOptions(await DeptAPI.getOptions(),'-1');
  deptOptions.value = [
    {
      id: "-1",
      name: "顶级部门",
      children: data,
    },
  ];

  dialog.visible = true;
  if (row) {
    dialog.title = "修改部门";
     Object.assign(formData, row);
  } else {
    dialog.title = "新增部门";
    formData.parentId = parentId || "-1";
  }
}

// 提交部门表单
function handleSubmit() {
  deptFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const deptId = formData.id;
      if (deptId) {
        DeptAPI.save({
			id:formData.id,
			parentId:formData.parentId,
			name:formData.name,
			code:formData.code,
			status:formData.status,
			sort:formData.sort,
			remark:formData.remark
		})
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        DeptAPI.save({
			id:"",
			parentId:formData.parentId,
			name:formData.name,
			code:formData.code,
			status:formData.status,
			sort:formData.sort,
			remark:formData.remark
		})
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 删除部门
function handleDelete(deptId?: string) {
  const deptIds = [deptId || selectIds.value].join(",");

  if (!deptIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      DeptAPI.deleteByIds(deptIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 重置表单
function resetForm() {
  deptFormRef.value.resetFields();
  deptFormRef.value.clearValidate();
  formData.id = undefined;
  formData.parentId = "-1";
  formData.status = '1';
  formData.code=undefined;
  formData.name=undefined;
  formData.remark="";
  formData.sort = 1;
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

onMounted(() => {
  handleQuery();
});
</script>
<style lang="scss" scoped>
	.left{
		width: 320px;
		margin-right: 10px;
	}
	.right{
		width: calc(100% - 220px);
	}
	.table-tool-bar{
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 5px;
	}
	:deep(.el-table th.el-table__cell) {
		/* background-color: #fafafa; */
		background-color: #eee;
		background-image: url();
		background-image: -webkit-linear-gradient(top, #f2f2f2 0, #fafafa 100%);
		background-image: -moz-linear-gradient(top, #f2f2f2 0, #fafafa 100%);
		background-image: -o-linear-gradient(top, #f2f2f2 0, #fafafa 100%);
		background-image: linear-gradient(to bottom, #f2f2f2 0, #fafafa 100%);
		font-size: 12px;
	}
</style>